package com.gushen.library;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.SurfaceHolder;

/**源码访问
 * git clone https://gitee.com/gushen/watermark-project.git
 *
 * 权限申请
 * implementation 'com.github.getActivity:XXPermissions:18.6'
 * XXPermissions.with(this)
 *             .permission(Permission.CAMERA)
 *             .permission(Permission.RECORD_AUDIO)
 *             .permission(Permission.WRITE_EXTERNAL_STORAGE)
 *             .request { _, all ->
 *                 if (all) {
 *                     startActivity(Intent(this, TargetActivity::class.java))
 *                 } else {
 *                     Toast.makeText(this, "权限异常", Toast.LENGTH_LONG).show()
 *                 }
 *                 finish()
 *             }
 */
public class MySurfaceView extends GLSurfaceView {

    private CameraRenderer cameraRenderer;

    public MySurfaceView(Context context) {
        super(context);
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);

        /**
         * 配置GLSurfaceView
         */
        //设置EGL版本
        setEGLContextClientVersion(2);
        cameraRenderer = new CameraRenderer(this);
        setRenderer(cameraRenderer);
        //设置按需渲染 当我们调用 requestRender 请求GLThread 回调一次 onDrawFrame
        // 连续渲染 就是自动的回调onDrawFrame
        setRenderMode(RENDERMODE_WHEN_DIRTY);

        if (watermarkConfig != null){
            cameraRenderer.setWatermarkConfig(watermarkConfig);
        }
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        super.surfaceDestroyed(holder);
        if (cameraRenderer != null){
            cameraRenderer.onSurfaceDestroyed();
        }
    }


    private WatermarkConfig watermarkConfig;
    public void setWatermarkConfig(WatermarkConfig config){
        this.watermarkConfig = config;
        if (cameraRenderer != null){
            cameraRenderer.setWatermarkConfig(config);
        }
    }

    public void startRecord() {
        float speed = 1f;
        if (cameraRenderer != null){
            cameraRenderer.startRecord(speed);
        }
    }

    public void stopRecord(RecorderCallBack callBack) {
        if (cameraRenderer != null){
            cameraRenderer.stopRecord(callBack);
        }
    }
}
